<template>
  <div id="app">
    <marking
      :init-config="{scrawlShow:false,markShow:false}"
      :always-show-mark-types="['fatiao']"
      :watermark="watermark"
      toolbox-height="60px"
      :load-fn="loadFn"
      :shadow-config="{shadowColor: 'blue',shadowBlur: 20}"
      :image-load-fn="imageLoadFn"
      :text-load-fn="textLoadFn"
      :whole-page="false"
      markline-color="red"
      @mark-click="handleMarkClick"
      @mark-mouseenter="handleMarkMouseenter"
      @clip-complete="clipComplete"
      @scrawl-complete="scrawlComplete"
      @contextmenu="contextmenu"
      @selection-change="selectionChange"
      @progress-change="progressChange"
      @page-change="pageChange"
      @page-unload="handlePageUnload"
      ref="marking">
      <template #toolbox="{ prop,method }">
        <div class="marking-tool-item" @click="method.zoomout" title="缩小">
          <img src="~@/assets/img/zoomout.png">
        </div>
        <div class="marking-tool-item" @click="method.zoomin" title="放大">
          <img src="~@/assets/img/zoomin.png">
        </div>
        <div class="marking-tool-item" title="选择缩放比例">
          <select v-model="prop.scaleType" @change="method.setScaleType(prop.scaleType)">
            <option value="page-actual">实际大小</option>
            <option value="page-fit">适合页面</option>
            <option value="page-width">适合页宽</option>
            <option :value="0.5">50%</option>
            <option :value="0.75">75%</option>
            <option :value="1">100%</option>
            <option :value="1.25">125%</option>
            <option :value="1.5">150%</option>
            <option :value="2">200%</option>
            <option :value="3">300%</option>
            <option :value="4">400%</option>
            <option :value="prop.scaleType" hidden>{{Math.round(prop.scaleType*100)}}%</option>
          </select>
        </div>
        <div class="marking-tool-item" @click="method.rotateCw" title="顺时针旋转90°">
          <img src="~@/assets/img/rotatecw.png">
        </div>
        <div class="marking-tool-item" @click="method.rotateCcw" title="逆时针旋转90°">
          <img src="~@/assets/img/rotateccw.png">
        </div>
        <div class="marking-tool-item" title="打开搜索框"
             @click="method.toggleSearchBoxShow">搜索
        </div>
        <div class="marking-tool-item" title="搜索曹操"
             @click="method.search('曹操')">搜索曹操
        </div>
        <div class="marking-tool-item" title="显示标记" v-show="!prop.markShow"
             @click="method.showMark">显示标记
        </div>
        <div class="marking-tool-item" title="隐藏标记" v-show="prop.markShow"
             @click="method.hideMark">隐藏标记
        </div>
        <div class="marking-tool-item" title="显示涂鸦" v-show="!prop.scrawlShow"
             @click="method.showScrawl">显示涂鸦
        </div>
        <div class="marking-tool-item" title="隐藏涂鸦" v-show="prop.scrawlShow" @click="method.hideScrawl">
          隐藏涂鸦
        </div>
        <div class="marking-tool-item" title="跳转页面" @click="method.skipByWordPos('4-50')">
          跳到5-50
        </div>
        <div class="marking-tool-item" title="涂鸦" @click="method.scrawl">涂鸦</div>
        <div class="marking-tool-item" title="截图" @click="method.clip">截图</div>
        <div class="marking-tool-item" title="上一页" @click="method.prevPage">上一页</div>
        <div class="marking-tool-item" title="下一页" @click="method.nextPage">下一页</div>
      </template>
      <template #markline="{data}">
        <div class="markline">
          <div class="markname">{{data.markname}}</div>
          <div class="marksm">{{data.marksm}}</div>
        </div>
      </template>
    </marking>
    <div class="selection-toolbar" ref="selectionToolbar" @pointerdown.stop>
      <div class="selection-toolbar-item" @click="handleSelectionToolbarItemClick(item)"
           v-for="(item,index) in toolbarList" :key="index">{{item.label}}
      </div>
    </div>
    <div class="selection-contextmenu" ref="selectionContextmenu" @pointerdown.stop>
      <div class="selection-contextmenu-item" @click="handleSelectionContextmenuItemClick(item)"
           v-for="(item,index) in contextmenuList" :key="index">{{item.label}}
      </div>
    </div>
  </div>
</template>

<script>
  // import Marking from './components/Marking/src/Component'
  import Marking, {SCRAWLTYPE} from './components/Marking'
  // import Marking from '..'

  // console.log(require('..'))

  // console.log(SCRAWLTYPE)

  // let dirName = 'test'

  const fileCount = 4

  let dirName = 'data'
  export default {
    name: 'app',
    components: {Marking},
    data() {
      return {
        toolbarList: [],
        contextmenuList: [],
        watermark: {
          text: '这个是水印',
          color: 'rgba(194,194,194,0.3)',
          fontSize: 80,
          rotation: 45,
          spacing: {
            x: 30,
            y: 30,
          }
        },
        textCacheList: {}
      }
    },
    computed: {
      marking() {
        return this.$refs.marking
      },
      selectionToolbar() {
        return this.$refs.selectionToolbar
      },
      selectionContextmenu() {
        return this.$refs.selectionContextmenu
      },
    },
    async mounted() {
      let scrawlList = JSON.parse(localStorage.getItem('scrawlList')) || []
      let markList = JSON.parse(localStorage.getItem('markList')) || []

      // markList.unshift({
      //   start: '0',
      //   end: JSON.stringify({
      //     height: 89.33255793595322,
      //     width: 655.9212473105604,
      //     x: 69.15124317989762,
      //     y: 846.7418120280147
      //   }),
      //   markline: {
      //     markname: '矩形标记',
      //     marksm: '截图'
      //   }
      // })
      markList.unshift({
        start: '0',
        end: JSON.stringify({
          x: 300,
          y: 300,
          width: 400,
          height: 300
        }),
        markline: {
          markname: '矩形标记',
          marksm: '矩形标记用于展示截图区域，印章区域，标题区域，等'
        }
      })

      let data = []
      let totalPage = 6
      for (let i = 0; i < totalPage; i++) {
        // let res = await fetch(`static/${dirName}/${i}.json`)
        // let text = await res.json()
        let m = i % fileCount
        data.push({
          // page: i,
          img: `static/${dirName}/${m}.jpg`,
          // text: text
        })
      }
      // let res = await fetch(`static/testData/testData.json`)
      // data = await res.json()

      await this.marking.open({data, scrawlList, markList})
      this.marking.setPointerType('hand')
      // this.marking.showMark()
      this.marking.addMark({
        start: '0-0',
        end: '0-20',
      })
      this.marking.addMark({
        start: '4-50',
        end: '5-20',
      })

      this.marking.addMark({
        start: '1-45',
        end: '1-60',
        config: {
          // strokeWidth: 5,
          stroke: 'red',
          type: 'underline'
        },
        type: 'fatiao'
      })
    },
    methods: {
      loadFn(arg) {
        // console.log(arg)
        return arg
      },
      imageLoadFn(arg) {
        // console.log(arg)
        // return `static/testData/img/${arg}.jpg`
        return new Promise((resolve, reject) => {
          // setTimeout(() => {
          resolve(arg)
          // }, 1000)
        })
      },
      async textLoadFn(pageIndex) {
        if (this.textCacheList[pageIndex]) return this.textCacheList[pageIndex]
        let res = await fetch(`static/${dirName}/${pageIndex % fileCount}.json`)
        // console.log(arg)
        // await new Promise((resolve, reject) => setTimeout(resolve, 5000))
        let text = await res.json()
        this.textCacheList[pageIndex] = text
        return text
      },
      clipComplete(clipData) {
        console.log('clipComplete', clipData)
      },
      handleMarkMouseenter(mark, evt) {
        console.log('handleMarkMouseenter', mark, evt)
      },
      handleMarkClick(mark, evt) {
        console.log('handleMarkClick', mark, evt)
      },
      scrawlComplete(scrawlData) {
        let scrawlList = JSON.parse(localStorage.getItem('scrawlList')) || []
        let index = scrawlList.findIndex(scrawlItem => scrawlItem.pageIndex === scrawlData.pageIndex)
        if (index > -1) scrawlList.splice(index, 1)
        scrawlList.push(scrawlData)
        localStorage.setItem('scrawlList', JSON.stringify(scrawlList))
      },
      selectionChange(selection) {
        if (!selection) return
        this.toolbarList = [
          {
            label: '复制文本',
            onclick: () => this.marking.copySelectText()
          },
          {
            label: '标注',
            onclick: () => {
              let markList = JSON.parse(localStorage.getItem('markList')) || []
              markList.push({
                start: selection.start,
                end: selection.end
              })
              localStorage.setItem('markList', JSON.stringify(markList))

              this.marking.addMark({
                start: selection.start,
                end: selection.end
              })
            }
          },
          {
            label: 'alert文本',
            onclick: () => window.alert(selection.text)
          }
        ]
        this.showSelectionToolbar()
      },
      showSelectionToolbar() {
        let pos = {x: 0, y: 0}
        if (event.type === 'touchend') {
          pos.x = event.changedTouches[0].pageX
          pos.y = event.changedTouches[0].pageY
        } else {
          pos.x = event.pageX
          pos.y = event.pageY
        }
        this.selectionToolbar.style.top = `${pos.y - this.selectionToolbar.offsetHeight - 10}px`
        this.selectionToolbar.style.left = `${pos.x - 30}px`
        this.selectionToolbar.style.visibility = 'visible'
        window.addEventListener("pointerdown", this.hideSelectionToolbar)
        window.addEventListener("wheel", this.hideSelectionToolbar, true)
      },
      hideSelectionToolbar() {
        this.selectionToolbar.style.visibility = 'hidden'
        window.removeEventListener("pointerdown", this.hideSelectionToolbar)
        window.removeEventListener("wheel", this.hideSelectionToolbar, true)
      },
      handleSelectionToolbarItemClick(item) {
        if (item.onclick) item.onclick()
        this.hideSelectionToolbar()
      },
      contextmenu(selection) {
        if (selection) {
          this.contextmenuList = [
            {
              label: '复制文本',
              onclick: () => this.marking.copySelectText()
            },
            {
              label: 'alert文本',
              onclick: () => window.alert(selection.text)
            }
          ]
        } else {
          this.contextmenuList = [
            {
              label: '这个是没有选中文本时的右键菜单',
              onclick: () => window.alert('这个是没有选中文本时的右键菜单的点击事件')
            },
            {
              label: '顺时针旋转90°',
              onclick: () => this.marking.rotateCw()
            },
            {
              label: '逆时针旋转90°',
              onclick: () => this.marking.rotateCcw()
            },
            {
              label: '调整至实际大小',
              onclick: () => this.marking.setScaleType('page-actual')
            },
            {
              label: '调整至适合页面',
              onclick: () => this.marking.setScaleType('page-fit')
            },
            {
              label: '调整至适合页宽',
              onclick: () => this.marking.setScaleType('page-width')
            }
          ]
        }
        this.showSelectionContextmenu()
      },
      showSelectionContextmenu() {
        this.selectionContextmenu.style.top = `${event.pageY - 10}px`
        this.selectionContextmenu.style.left = `${event.pageX + 10}px`
        this.selectionContextmenu.style.visibility = 'visible'
        window.addEventListener("pointerdown", this.hideSelectionContextmenu)
        window.addEventListener("wheel", this.hideSelectionContextmenu, true)
      },
      hideSelectionContextmenu() {
        this.selectionContextmenu.style.visibility = 'hidden'
        window.removeEventListener("pointerdown", this.hideSelectionContextmenu)
        window.removeEventListener("wheel", this.hideSelectionContextmenu, true)
      },
      handleSelectionContextmenuItemClick(item) {
        if (item.onclick) item.onclick()
        this.hideSelectionContextmenu()
      },
      progressChange(a) {
        // console.log(a)
      },
      pageChange(a) {
        // console.log(a)
      },
      handlePageUnload(e) {
        console.log(e)
      }
    }
  }
</script>

<style lang="scss">
  html, body {
    margin: 0;
    padding: 0;
  }
</style>
<style lang="scss" scoped>
  #app {
    width: 100vw;
    height: 100vh;
    cursor: default;

    .marking-tool-item {
      font-size: 14px;
      /*display: inline-block;*/
      box-sizing: border-box;
      max-height: calc(100% - 10px);
      border-radius: 5px;
      margin-top: 5px;
      margin-left: 5px;
      vertical-align: middle;

      &.active {
        background-color: #cccccc;
        color: #fff;
      }

      img {
        box-sizing: border-box;
        padding: 2px;
        height: 20px;
      }

      &:hover {
        background-color: #cccccc;
        color: #fff;
      }

      select {
        height: 100%;
        width: 100%;
        border: none;
        outline: none;
        background-color: transparent;
        appearance: none;
        background-position: right center;
        background-repeat: no-repeat;
        background-size: 20px;
        background-image: url("./assets/img/arrow_right.png");
        padding-right: 20px;
        padding-left: 10px;

        /*option {*/
        /*  background-color: red;*/
        /*}*/
      }
    }

    .markline {
      width: 200px;
      background-color: #409EFF;
    }

    .selection-toolbar {
      position: absolute;
      top: 0;
      left: 0;
      background-color: white;
      border-radius: 3px;
      border: 1px solid #ccc;
      visibility: hidden;

      .selection-toolbar-item {
        display: inline-block;
        padding: 0 5px;
        line-height: 30px;
        border-right: 1px solid #ccc;

        &:nth-last-child(1) {
          border-right: none;
        }

        &:hover {
          background-color: #cccccc;
        }
      }

    }

    .selection-contextmenu {
      position: absolute;
      top: 0;
      left: 0;
      background-color: white;
      border-radius: 3px;
      border: 1px solid #ccc;
      visibility: hidden;

      .selection-contextmenu-item {
        text-indent: 20px;
        line-height: 30px;
        padding-right: 10px;
        border-bottom: 1px solid #ccc;

        &:nth-last-child(1) {
          border-bottom: none;
        }

        &:hover {
          background-color: #ccc;
        }
      }
    }
  }
</style>
